/** 
 * Copyright 2010 Erlacher Felix, Estgfaeller Wolfgang, Ferula Patrick
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package at.socialconference.app.twitter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import twitter4j.Relationship;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.http.AccessToken;
import twitter4j.http.RequestToken;
import at.socialconference.Controller;
import at.socialconference.app.connection.ConnectionHandler;
import at.socialconference.app.model.AUser;

public class TwitterHelper {

	public final static String CONSUMER_KEY = "6VTFnlk9V4ZvGlhREQoKYg";
	public final static String CONSUMER_SECRET = "cMqcPBf8S9yU1E56n6MUDEhs5KQ33kRCfWehvqagjSE";

	private static RequestToken requestToken;

	private static Twitter getTwitter(boolean hasTokens){
		TwitterFactory tf = new TwitterFactory();
		if(hasTokens){
			AUser u = Controller.getUser();
			AccessToken ac = new AccessToken(u.getTw_access_token(), u.getTw_access_secret());
			return tf.getOAuthAuthorizedInstance(CONSUMER_KEY, CONSUMER_SECRET, ac);
		}else{
			return tf.getOAuthAuthorizedInstance(CONSUMER_KEY, CONSUMER_SECRET);
		}
	}


	public static boolean tweet(String tweet){
		try {
			Twitter twitter = getTwitter(true);
			twitter.updateStatus(tweet);
			return true;
		} catch (TwitterException e) {
			e.printStackTrace();
			return false;
		}
	}

	public static int setPin(String pin){ 
		if(pin!=null){
			AccessToken accessToken = createAccToken(pin);
			String tokenTxt = accessToken.getToken();
			String secretTxt = accessToken.getTokenSecret();
			Controller.getUser().setTw_access_token(tokenTxt);
			Controller.getUser().setTw_access_secret(secretTxt);
			return ConnectionHandler.addTwitterTokens(tokenTxt,secretTxt);
		}else{
			return -1;
		}
	}

	/**
	 * as soon as user has pin this method is called and an access token should
	 * be created and ev. saved in DB for every user.
	 * 
	 * @param pin
	 */
	private static AccessToken createAccToken(String pin) {
		try {
			Twitter twitter = getTwitter(false);
			if (pin.length() > 0) {
				return twitter.getOAuthAccessToken(requestToken, pin);
			} else {
				return twitter.getOAuthAccessToken();
			}
		} catch (TwitterException te) {
			if (401 == te.getStatusCode()) {
				te.printStackTrace();
			} else {
				te.printStackTrace();
			}
			return null;
		}

	}


	public static String getAuthURL() {
		requestToken = null;
		try {
			requestToken = getTwitter(false).getOAuthRequestToken();
			return requestToken.getAuthorizationURL();
		} catch (TwitterException e) {
			e.printStackTrace();
		}
		return null;
	}


	public static Integer follow(int id) {
		try {
			getTwitter(true).createFriendship(id);
			return 1;
		} catch (TwitterException e) {
			if (403 == e.getStatusCode()) {
				System.out.println("-----Already friends!");
				return 2;
			} else if(401 == e.getStatusCode()){
				System.out.println("-----App Access Denied?!");
				return -2;
			}else {
				e.printStackTrace();
				return -1;
			}
		}
	}


	public static Integer unFollow(int id) {
		try {
			getTwitter(true).destroyFriendship(id);
			return 1;
		} catch (TwitterException e) {
			if (403 == e.getStatusCode()) {
				System.out.println("-----never been friends?");
				return 2;
			}else if(401 == e.getStatusCode()){
				System.out.println("-----App Access Denied?!");
				return -2;
			} else {
				e.printStackTrace();
				return -1;
			}
		}
	}

	public static boolean isFollowing(Integer id) {
		try {
			Twitter tw = getTwitter(true);
			Relationship r = tw.showFriendship(tw.getId(), id);
			return r.isSourceFollowingTarget();
		} catch (TwitterException e) {
			e.printStackTrace();
			return false;
		}
	}


	public static List<String> getTimelines(Integer id) {
		List<Status> statuses = null;
		List<Status> ret = new ArrayList<Status>();
		try {
			statuses = getTwitter(true).getFriendsTimeline();
			
			for(Status status : statuses){
				User u = status.getUser();
				if(u.getId() == id.intValue()){
					ret.add(status);
				}
			}
			return createStatusString(ret);
			
		} catch (TwitterException e) {
			if(401 == e.getStatusCode()){
				System.out.println("-----App Access Denied?!\n");
			}
			e.printStackTrace();
			return null;
		}
	}


	private static List<String> createStatusString(List<Status> stats) {
		List<String> ret = new ArrayList<String>();
		for(Status status : stats){
			SimpleDateFormat sdf = new SimpleDateFormat("dd.MM HH:mm");
			String tmp = sdf.format(status.getCreatedAt())+"\n";
			tmp += status.getText();
			ret.add(tmp);
		}
		return ret;
	}
}
